package com.umeox.quranplayer.viewmodel

import android.content.Context
import android.os.PowerManager
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.umeox.moto.common.log.Logger
import com.umeox.quranplayer.base.BaseApp
import com.umeox.quranplayer.event.ChallengeEvent
import org.greenrobot.eventbus.EventBus
import java.util.*

/**
 * Created by Rambo 2022/1/7
 * Describe:
 */
class TimerViewModel : ViewModel() {

    private val ONE_SECOND = 1000L

    val mElapsedTimeLiveData: MutableLiveData<Long> = MutableLiveData<Long>()

    private var mInitialTime: Long = 0
    private var timer: Timer? = null

    private var mWakeLock: PowerManager.WakeLock? = null

    fun start(targetTime: Long) {
        Logger.e("=======targetTime=$targetTime")
        mInitialTime = 0
        timer = Timer()
        acquireWakeLock()
        // 每隔一秒更新一次
        timer?.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                mInitialTime += 1
                Logger.e("=======mInitialTime=$mInitialTime")
                if (mInitialTime == targetTime) {
                    Logger.e("=======post ChallengeEvent===========")
                    EventBus.getDefault().post(ChallengeEvent(mInitialTime))
                }
                mElapsedTimeLiveData.postValue(mInitialTime)

            }
        }, ONE_SECOND, ONE_SECOND)

    }

    fun pause() {
        Logger.e("=======timer pause=========")
        timer?.cancel()
        releaseWakeLock()

    }

    fun end() {
        mInitialTime = 0
        timer?.cancel()
        releaseWakeLock()
    }


    //申请设备电源锁
    private fun acquireWakeLock() {
        if (null == mWakeLock) {
            val pm = BaseApp.getInstance().getSystemService(Context.POWER_SERVICE) as PowerManager
            mWakeLock = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ON_AFTER_RELEASE,
                TimerViewModel::class.java.simpleName
            )
            if (null != mWakeLock) {
                mWakeLock?.acquire()
            }
        }
    }

    //释放设备电源锁
    private fun releaseWakeLock() {
        if (mWakeLock != null) {
            try {
                mWakeLock?.release()
            } catch (th: Throwable) {
                // ignoring this exception, probably wakeLock was already released
            }
        } else {
            // should never happen during normal workflow
            Logger.w(">>>Wakelock reference is null")
        }
        mWakeLock = null
    }

}